import pandas as pd
import itertools
import gradio as gr

# 你的电芯数据（可替换为数据库查询或CSV文件）
电芯数据 = [
    {"品牌": "宁德时代", "类型": "三元锂", "规格型号": "18650", "尺寸": "18*65*91"},
    {"品牌": "比亚迪", "类型": "磷酸铁锂", "规格型号": "21700", "尺寸": "21*70*148"},
    {"品牌": "松下", "类型": "三元锂", "规格型号": "18650", "尺寸": "18*65*91"},
    # 可继续添加更多电芯...
]


def calculate_battery_layout(warehouse_dim, num_cells):
    df = pd.DataFrame(电芯数据)  # 固定数据

    # 解析电池仓尺寸
    try:
        l, w, h = map(float, warehouse_dim.split('*'))
    except:
        return "尺寸格式错误（需为长*宽*高）", None

    best_cells = []
    best_utilization = 0

    for pb_pos in [1, 2, 3, 4, 5, 6]:
        if pb_pos in [1, 2]:
            usable = (l, w, h - 30)
        elif pb_pos in [3, 4]:
            usable = (l, w - 30, h)
        else:
            usable = (l - 30, w, h)

        for idx, row in df.iterrows():
            size = row['尺寸']
            try:
                cl, cw, ch = map(float, size.split('*'))
            except:
                continue

            for orient in itertools.permutations([cl, cw, ch]):
                ol, ow, oh = orient
                rows = int(usable[0] // ol)
                cols = int(usable[1] // ow)
                layers = int(usable[2] // oh)
                total = rows * cols * layers

                if total >= num_cells:
                    cell_volume = cl * cw * ch
                    utilization = (num_cells * cell_volume) / (l * w * h)
                    best_cells.append({
                        "品牌": row['品牌'],
                        "型号": f"{row['类型']}-{row['规格型号']}",
                        "尺寸": ']}",
                                "尺寸": size,
                    "利用率": utilization,
                    "最大数量": total,
                    "保护板位置": pb_pos,
                    "排列": f"{ol}x{ow}x{oh}"
                    })
                    if utilization > best_utilization:
                        best_utilization = utilization

    if best_cells:
        df_result = pd.DataFrame(best_cells)
        df_result = df_result.sort_values("利用率", ascending=False).head(5)
        return f"推荐方案（按利用率排序）", df_result
    else:
        return "未找到合适方案，请调整参数", None


# 创建网页界面（无文件上传）
with gr.Blocks(title="电池布局计算器") as demo:
    gr.Markdown("# 📦 电池仓布局优化工具（用户版）")

    with gr.Row():
        with gr.Column():
            # 尺寸输入
            dim_input = gr.Textbox(
                label="电池仓尺寸（长*宽*高，mm）",
                value="220*165*350",
                placeholder="示例：220*165*350"
            )
            # 数量输入
            num_input = gr.Slider(
                label="电芯数量",
                minimum=1,
                maximum=200,
                value=20,
                step=1
            )
            # 计算按钮
            btn = gr.Button("计算最佳方案", variant="primary")

        with gr.Column():
            result_text = gr.Textbox(label="计算结果", lines=2)
            result_table = gr.Dataframe(
                label="最优电芯方案",
                headers=["品牌", "型号", "尺寸", "利用率", "最大数量", "保护板位置", "排列"],
                max_rows=5
            )

    # 绑定计算函数
    btn.click(
        fn=calculate_battery_layout,
        inputs=[dim_input, num_input],
        outputs=[result_text, result_table]
    )

if __name__ == "__main__":
    demo.launch(share=True)  # 生成可分享链接